package com.sam.im.heiqun.uis.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.pay.PayResult;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGApi;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.beans.GetVipNumBean;
import com.sam.im.heiqun.uis.beans.RechargeOrderBean;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.EventBusType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/9/19.
 */

public class LiangSelecterPayTypeActivity extends BaseSwipeBackActivity {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.txt_price)
    TextView txt_price;
    @BindView(R.id.radio_wx)
    RadioButton radio_wx;

    private PGService pgservice;
    private static final int SDK_PAY_FLAG = 1;

    private String sessionid = "";
    private GetVipNumBean.ListBean listBean ;
    private String headUrl = "";
    private String mobile = "";
    private String pwd = "";
    private String name = "";
    private String validateNum = "";

    private int type = 0 ;//0-是未注册直接购买；1-已注册，购买靓号
    private String uid = "";
    private String price = "";
    private String num = "";

    private IWXAPI api;

    public static void start(Activity activity, String sessionid, GetVipNumBean.ListBean listBean,
                             String headUrl, final String mobile, final String pwd, String name, String validateNum){

        Intent intent = new Intent(activity, LiangSelecterPayTypeActivity.class);
        intent.putExtra("sessionid",sessionid);
        intent.putExtra("listBean",listBean);
        intent.putExtra("headUrl",headUrl);
        intent.putExtra("mobile",mobile);
        intent.putExtra("pwd",pwd);
        intent.putExtra("name",name);
        intent.putExtra("validateNum",validateNum);
        activity.startActivity(intent);

    }
    public static void start(Activity activity, int type, String uid , String price, String num){
        Intent intent = new Intent(activity, LiangSelecterPayTypeActivity.class);
        intent.putExtra("type",type);
        intent.putExtra("uid",uid);
        intent.putExtra("price",price);
        intent.putExtra("num",num);
        activity.startActivity(intent);
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.select_im);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        pgservice = PGService.getInstance();

        api = WXAPIFactory.createWXAPI(this, PGApi.WX_APP_ID);
        api.registerApp(PGApi.WX_APP_ID);

        type = getIntent().getIntExtra("type", 0);
        if (1 == type){
            uid = getIntent().getStringExtra("uid");
            price = getIntent().getStringExtra("price");
            num = getIntent().getStringExtra("num");
            txt_price.setText("￥：" + price);
        }else {
//        String headUrl, final String mobile, final String pwd, String name, String validateNum
            sessionid = getIntent().getStringExtra("sessionid");
            headUrl = getIntent().getStringExtra("headUrl");
            mobile = getIntent().getStringExtra("mobile");
            pwd = getIntent().getStringExtra("pwd");
            name = getIntent().getStringExtra("name");
            validateNum = getIntent().getStringExtra("validateNum");
            listBean = (GetVipNumBean.ListBean) getIntent().getSerializableExtra("listBean");

            txt_price.setText("￥：" + listBean.getPrice());
        }

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_liang_selecter_pay;
    }

    @OnClick({R.id.register})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.register :
                String types = "";
                if (radio_wx.isChecked()){
                    types = "wxpay";
                }else {
                    types = "alipay";
                }
                if (1 == type){
                    register(types, price, num);
                }else {
                    num = listBean.getNum();
                    register(types, listBean.getPrice(), listBean.getNum());
                }

                break;
        }
    }

    /**
     * 注册接口
     */
    private void register(final String type, String price, String num) {
        showProgress(getResources().getString(R.string.now_down));
        pgservice.createNumberOrder(price, "heiqun", headUrl, mobile, name, num, pwd, sessionid, getResources().getString(R.string.buy_im), type, validateNum, uid).subscribe(new AbsAPICallback<RechargeOrderBean>() {
            @Override
            public void onNext(final RechargeOrderBean rechargeOrderBean) {
                if ("wxpay".equals(type)){
                    com.alibaba.fastjson.JSONObject json = JSON.parseObject(rechargeOrderBean.getOrderString());

                    PayReq req = new PayReq();
                    //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                    req.appId			= json.getString("appid");
//                    req.appId			= PGApi.WX_APP_ID;
                    req.partnerId		= json.getString("partnerid");
                    req.prepayId		= json.getString("prepayid");
                    req.nonceStr		= json.getString("noncestr");
                    req.timeStamp		= json.getString("timestamp");
                    req.packageValue	= json.getString("package");
                    req.sign			= json.getString("sign");
                    req.extData			= "app data"; // optional
//                    Toast.makeText(RechargeActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    api.sendReq(req);
                    hideProgress();
                }else if ("alipay".equals(type)){
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(LiangSelecterPayTypeActivity.this);
                            Map<String, String> result = alipay.payV2(rechargeOrderBean.getOrderString(), true);
                            Log.i("msp", result.toString());

                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };

                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                    hideProgress();
                }

            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                String exStr = ex.getDisplayMessage();
                // 因为返回值 可能为 Json 数据,需要解析再展示
                try {
                    com.alibaba.fastjson.JSONObject json = JSON.parseObject(exStr);
                    com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                    String info = data.getString("info");
                    showToast(info);
                }catch (Exception e){
                    showToast(ex.getDisplayMessage());
                    e.printStackTrace();
                }

            }
        });
    }

    int checkNum = 0 ;

    /**
     * 注册接口
     */
    private void checkNumber() {
        if (1 == type){
            UserEntivity userEntivity =  ToolsUtils.getUser();
            if (null!=userEntivity){
                userEntivity.setIMNo(num);
                userEntivity.save();

            }
        }else {
            showProgress(getResources().getString(R.string.now_down));
            pgservice.checkNumber(listBean.getNum()).subscribe(new AbsAPICallback<RechargeOrderBean>() {
                @Override
                public void onNext(final RechargeOrderBean rechargeOrderBean) {

                    //退回到登录页面
                    EventBus.getDefault().post(EventBusType.RESULT_PAY_LIANG_SUCCESS);
                    finish();
                }

                @Override
                protected void onResultError(ApiException ex) {
                    if (checkNum < 3){
                        checkNum++;
                        checkNumber();
                    }else {
                        showToast(getResources().getString(R.string.im_apply_fail));
                        hideProgress();
                    }

                }
            });
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer refresh) {
        if (refresh == EventBusType.RESULT_PAY_WX_SUCCESS){
            checkNumber();
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(LiangSelecterPayTypeActivity.this, getResources().getString(R.string.pay_success), Toast.LENGTH_SHORT).show();
//
                        checkNumber();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(LiangSelecterPayTypeActivity.this, getResources().getString(R.string.pay_fail), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };

}
